package org.unei.common.helper;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by sunlei on 2015/7/17.
 */
public class ObjectFinder {
    private static ObjectFactory objectFactory=new ObjectFactoryImpl();

    public interface ObjectFactory{
        public Object create(String clazzName)throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException;
    }

    protected static class ObjectFactoryImpl implements ObjectFactory{
        static final ConcurrentHashMap<String,Class> classMap=new ConcurrentHashMap<String,Class>();

        @Override
        public Object create(String clazzName) throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException {
            Class clazz=classMap.get(clazzName);
            if(clazz==null){
                clazz=loadClass(clazzName);
                if(clazz==null)
                    throw new ClassNotFoundException("Could not find class:"+clazzName);
            }
            return clazz.newInstance();
        }

        public static Class loadClass(String clazzName){
            Class clazz=null;
            ClassLoader loader=Thread.currentThread().getContextClassLoader();
            if(loader!=null){
                try {
                    clazz=loader.loadClass(clazzName);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }

            return clazz;
        }
    }

    public static <T> T newInstance(String clazzName) throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException {
        return (T)objectFactory.create(clazzName);
    }
}
